package com.tool.sqlexecutor.sql;

import com.tool.sqlexecutor.config.DataSourceProperty;
import com.tool.sqlexecutor.util.SSHClient;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;
import java.util.List;

public class MultiDataSourceQuery {
    private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    private List<DataSourceProperty> dataSourceProperties;
    private String sql;

    public MultiDataSourceQuery(List<DataSourceProperty> dataSourceProperties, String sql) {
        this.dataSourceProperties = dataSourceProperties;
        this.sql = sql;
    }

    public String query() {
        StringBuilder stringBuilder = new StringBuilder();
        for (DataSourceProperty dataSourceProperty : dataSourceProperties) {
            queryOneDataSource(dataSourceProperty, stringBuilder);
        }
        return stringBuilder.toString();
    }

    private void queryOneDataSource(DataSourceProperty dataSourceProperty, StringBuilder stringBuilder) {
        stringBuilder.append("database:" + dataSourceProperty.getDatabase())
                .append("\n")
                .append("url:" + dataSourceProperty.getUrl())
                .append("\n");
        SSHClient client = new SSHClient(dataSourceProperty.getSsh(), dataSourceProperty);
        try {
            client.start();
            DataSource dataSource = client.getDataSource();

            DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
            transactionManager.setEnforceReadOnly(true);
            transactionManager.getTransaction(new DefaultTransactionDefinition());

            JdbcTemplate template = new JdbcTemplate(dataSource);
            SqlRowSet sqlRowSet = template.queryForRowSet(sql);
            String format = new ResultPrinter(sqlRowSet).format();
            stringBuilder.append(format).append("\n");
        } catch (Exception e) {
            stringBuilder.append(e.getMessage().replaceAll(";", ";\n\t\t"));
        } finally {
            client.end();
        }
    }
}
